# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql

class PycharmScrapyPipeline:
    def __init__(self):
        # 建立连接
        self.conn = pymysql.connect(host="localhost",user="root",password="",port=3306,db="weiyi",charset="utf8")  # 因为有中文要存入数据库因此要加charset='utf8'
        # 创建游标
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        # sql语句
        insert_sql = """
        insert into doctor(name,job,subject,hospital,star,number,image,video,skill) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)
        """
        # 执行插入数据到数据库操作
        self.cursor.execute(insert_sql,(item['doctor_name'],item['doctor_job'],item['doctor_subject'],item['doctor_hospital'],
                                        item['doctor_star'],item['doctor_number'],item['doctor_image'],item['doctor_video'],item['doctor_skill']))
        # 提交保存到数据库
        self.conn.commit()
        return item

    def close_spider(self,spider):
        # 关闭游标和连接
        self.cursor.close()
        self.conn.close()